package com.fancy.mobileschool.service;


import com.fancy.mobileschool.entity.Course;
import com.fancy.mobileschool.entity.YunFile;
import com.fancy.mobileschool.util.GsonUtil;
import com.fancy.mobileschool.util.OKHttpUtil;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Jackie on 2017/11/12.
 */

public class YunFileService {

    private OkHttpClient httpClient = OKHttpUtil.getHttpClient();

    private Gson gson = GsonUtil.getGson();

    private static final String baseUrl =  "http://120.78.197.155:8080/MobileSchool-chat/yun_file";

    private static final String yun2 = "http://101.200.35.107:8080/MobileSchool-chat/group_chat";

    private static final String baseUrl1 = "http://192.168.1.101:8081/yun_file";

    private static final String baseUrlForPerson = baseUrl + "/person/";

    private static final String baseUrlForCourse = baseUrl + "/course/";

    public List<YunFile> getMyYunFiles(String myID) {
        List<YunFile> rs;
        String url = baseUrl + "/getMyFile.do?myID=" + myID;
        rs = OKHttpBase.fromJsonListByGet(url, YunFile.class);

        return rs;
    }

    public List<Course> getShareCourse() {
        List<Course> rs ;
        String url = baseUrlForCourse + "getShareCourse.do";
        rs = OKHttpBase.fromJsonListByGet(url, Course.class);
        return rs;
    }

    public List<Course> getMyCourses() {
        return getShareCourse();
    }

    public List<YunFile> getCourseShareFiles(String course_name) {
        List<YunFile> rs;
        String url = baseUrlForCourse + "getCourseShareFiles.do?course_name=" + course_name;
        rs = OKHttpBase.fromJsonListByGet(url, YunFile.class);
        return rs;
    }

    public boolean uploadPersonFile(File file, String myID) {
        String url = baseUrlForPerson + "uploadFile.do?myID=" + myID;
        return uploadFile(url, file);
    }

    public boolean uploadCourseFile(File file, String course_id, String myID) {
        String url = baseUrlForCourse + "uploadFile.do?course_name=" + course_id + "&myID=" + myID;
        return uploadFile(url, file);
    }

    private boolean uploadFile(String url, File file) {
        RequestBody filebody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody body = new MultipartBody.Builder()
                .addFormDataPart("file", file.getName(), filebody)
                .build();
        final Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
        } catch (IOException e) {

        }

        return response.code() == 200;
    }

}
